package router

import (
	"github.com/rs/zerolog"
	"go-ecommerce/internal/controller/admin"
	"go-ecommerce/internal/middleware"
	"go-ecommerce/internal/utils"
	"gorm.io/gorm"

	"github.com/gin-gonic/gin"
	"github.com/swaggo/files"
	"github.com/swaggo/gin-swagger"
)

// SetupRouter 设置路由
func SetupRouter(db *gorm.DB) *gin.Engine {
	// 设置Gin模式
	if utils.Logger.GetLevel() == zerolog.FatalLevel {
		gin.SetMode(gin.ReleaseMode)
	} else {
		gin.SetMode(gin.DebugMode)
	}

	// 创建默认引擎
	r := gin.Default()

	// 注册中间件
	r.Use(middleware.ErrorHandler())

	// 鉴权保护的接口组

	// 注册Swagger文档路由
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	// 需要登录的接口
	adminGroup := r.Group("/admin")
	{
		// 登录
		adminGroup.POST("/login", admin.LoginHandle)
		adminGroup.GET("/captcha", admin.GetCaptcha)

		// 需要登录的接口
		adminGroup.Use(middleware.JWTAuthMiddleware(), middleware.PermissionMiddleware(db))
		//adminGroup.Use(middleware.JWTAuthMiddleware())
		{

			// 分类管理
			adminGroup.GET("/category", admin.GetCategoryListHandler(db))       // 列表
			adminGroup.POST("/category", admin.CreateCategoryHandler(db))       // 新增
			adminGroup.PUT("/category/:id", admin.UpdateCategoryHandler(db))    // 修改
			adminGroup.DELETE("/category/:id", admin.DeleteCategoryHandler(db)) // 删除

			adminGroup.POST("/admin", admin.CreateAdminHandler(db)) //添加管理员
			adminGroup.PUT("/admin/:id", admin.UpdateAdminHandler(db))
			adminGroup.DELETE("/admin/:id", admin.DeleteAdminHandler(db))
			adminGroup.GET("/admin", admin.ListAdminHandler(db))
			adminGroup.GET("/admin/:id", admin.AdminInfoHandler(db))

			adminGroup.POST("/role", admin.CreateRoleHandler(db))
			adminGroup.PUT("/role/:id", admin.UpdateRoleHandler(db))
			adminGroup.DELETE("/role/:id", admin.DeleteRoleHandler(db))
			adminGroup.GET("/role/:id", admin.GetRoleHandler(db))
			adminGroup.GET("/role", admin.GetAllRoleHandler(db))

			adminGroup.POST("/permission", admin.CreatePermissionHandler(db))
			adminGroup.GET("/permission", admin.ListPermissionHandler(db))
			adminGroup.PUT("/permission/:id", admin.UpdatePermissionHandler(db))
			adminGroup.DELETE("/permission/:id", admin.DeletePermissionHandler(db))

			adminGroup.POST("/role-permission", admin.AssignPermissionsHandler(db))          //给角色分配权限
			adminGroup.GET("/role-permission/:role_id", admin.GetRolePermissionsHandler(db)) //获取权限

			adminGroup.POST("/bind_roles", admin.BindRolesHandler(db)) //获取权限

			adminGroup.POST("/menu", admin.CreateOrUpdateMenuHandler(db)) // 菜单创建或更新
			adminGroup.GET("/menu", admin.GetMenuListHandler(db))         // 菜单列表
			adminGroup.DELETE("/menu/:id", admin.DeleteMenuHandler(db))   // 菜单删除
			adminGroup.GET("/tree", admin.GetMenuTreeHandler(db))         // 获取权限绑定菜单树
		}
	}

	return r
}
